package com.zkingsoft.actions.admin;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.zkingsoft.actions.common.BaseController;
import com.zkingsoft.anotations.RemoveRequestToken;
import com.zkingsoft.anotations.SaveRequestToken;
import com.zkingsoft.exception.GlobleException;
import com.zkingsoft.model.Bonus;
import com.zkingsoft.model.BonusDetail;
import com.zkingsoft.model.Bonusinfo;
import com.zkingsoft.model.Course;
import com.zkingsoft.model.Paymentinfo;
import com.zkingsoft.model.Studentinfo;
import com.zkingsoft.plugin.pojo.PaginationVO;
import com.zkingsoft.plugin.util.DateUtils;
import com.zkingsoft.plugin.util.ExcelImport;
import com.zkingsoft.plugin.util.ExcelUtil;
import com.zkingsoft.plugin.util.FileDownload;
import com.zkingsoft.plugin.util.FileUtils;
import com.zkingsoft.plugin.util.WebUtil;
import com.zkingsoft.plugin.util.ExcelUtil.ViewExcel;
import com.zkingsoft.pojo.AjaxResult;
import com.zkingsoft.services.BonusService;
import com.zkingsoft.services.BonusinfoService;
import com.zkingsoft.services.PaymentinfoService;
import com.zkingsoft.services.StudentinfoService;
import com.zkingsoft.services.TabClassService;

/**
 * 奖金明细controller
 * 
 * @date 2016-11-17 11:32
 */
@Controller
@RequestMapping(value = "admin/bonusinfo")
public class BonusinfoController extends BaseController {

	@Resource
	private BonusinfoService bonusinfoService;
	@Resource
	private BonusService bonusService;
	@Resource
	private StudentinfoService studentService;
	@Resource
	private TabClassService tabClassService;
	@Resource
	private PaymentinfoService paymentinfoService;

	/**
	 * 列表显示
	 */
	@RequestMapping(value = "/showList")
	public @ResponseBody AjaxResult showList(Bonusinfo bonusinfo, PaginationVO pageVo) {
		return showList(bonusinfoService, bonusinfo, pageVo);
	}

	/**
	 * 新增或者修改页面
	 */
	@RemoveRequestToken
	@RequestMapping(value = "/addOrModify")
	public @ResponseBody AjaxResult addOrModify(Bonusinfo bonusinfo) {
		Paymentinfo paymentinfo = paymentinfoService.findBysId(bonusinfo.getsId());
		// 判断该学生是否有交学费
		if (paymentinfo == null) {
			throw new GlobleException("该学生没有交学费");
		}
		//判断交清学费才能添加奖金信息
		
		
		// 判断领款总金额是否大于总奖金金额
		double ling = 0.0;
		for (BonusDetail bonusDetail : bonusinfo.getBdList()) {
			if (bonusDetail.getBdMoney() != null) {
				ling += bonusDetail.getBdMoney();
			}
		}
		if (ling > bonusinfo.getBiMoney()) {
			throw new GlobleException("领款总金额不能大于奖金金额");
		}
		if (bonusinfo.getBiId() != null) {
			return modify(bonusinfoService, bonusinfo, "奖金明细");
		} else {
			return add(bonusinfoService, bonusinfo, "奖金明细");
		}
	}

	/**
	 * 进入修改界面
	 */
	@SaveRequestToken
	@RequestMapping(value = "/editForm")
	public String editForm(Long id) {
		Bonusinfo bonusinfo;
		if (id != null) {
			bonusinfo = bonusinfoService.findById(id);
			WebUtil.getRequest().setAttribute("obj", bonusinfo);
		}
		return "admin/bonusinfo-form";
	}

	/**
	 * 删除
	 */
	@RequestMapping(value = "/del")
	public @ResponseBody AjaxResult del(String keys) {
		return remove(bonusinfoService, keys);
	}

	/**
	 * @Description:显示所有的奖金名目
	 * @author:dingchuan
	 * @param bonusinfo
	 * @param pageVo
	 * @return 返回类型 AjaxResult
	 * @date 2017年2月14日
	 */
	@RequestMapping(value = "/showBonusList")
	public @ResponseBody AjaxResult showBonusList() {
		List<Bonus> bonusList = bonusService.findByModel(null);
		return new AjaxResult(AjaxResult.STATUS_OK, "", "", bonusList, bonusList.size());
	}

	
	/**
	 * 
	 * @date :2017年6月23日
	 * @author:laotie
	 * @param bonus
	 * @return
	 */
	@RequestMapping(value = "/changeMoney")
	public @ResponseBody AjaxResult changeMoney(Bonus bonus) {
		if (bonus.getbName() != null && bonus.getbName().equals("")) {
			try {
				bonus.setbName(java.net.URLDecoder.decode(bonus.getbName(), "UTF-8"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		List<Bonus> stuList = bonusService.findByModel(bonus);
		if (stuList != null && stuList.size() > 0) {
			return new AjaxResult(AjaxResult.STATUS_OK, null, "成功", stuList, stuList.size());
		}
		return new AjaxResult(AjaxResult.STATUS_ERR, null, "没有");
	}

	/**
	 * 
	 * @Description:导出excel
	 * @author:dingchuan
	 * @return 返回类型 ModelAndView
	 * @date 2017年2月13日
	 */
	/*
	 * @RequestMapping(value = "/exportExcel") public @ResponseBody ModelAndView
	 * report(ModelMap model, HttpServletRequest request, HttpServletResponse
	 * response, Bonusinfo bonusinfo) { try { if (bonusinfo.getsName() != null
	 * && !(bonusinfo.gettuName().equals(""))) {
	 * bonusinfo.setsName(java.net.URLDecoder.decode(bonusinfo.getstuName(),
	 * "UTF-8")); } if (bonusinfo.getBiOption1() != null &&
	 * !(bonusinfo.getBiOption1().equals(""))) {
	 * bonusinfo.setBiOperator(java.net.URLDecoder.decode(bonusinfo.getBiOption1
	 * (), "UTF-8")); } if (bonusinfo.getbPayee() != null &&
	 * !(bonusinfo.getbPayee().equals(""))) {
	 * bonusinfo.setbPayee(java.net.URLDecoder.decode(bonusinfo.getbPayee(),
	 * "UTF-8")); } } catch (UnsupportedEncodingException e1) {
	 * e1.printStackTrace(); } // 查询符合条件的数据 List<Bonusinfo> dataList =
	 * bonusinfoService.findByModel(bonusinfo);
	 * //把数据组装成我们要的数据，外面的list表示一行数据，也就是一个对象的信息，对应到excel的一行数据。里面的list表示对象的一个属性，
	 * 对应excel的单元格 SimpleDateFormat sdf = new
	 * SimpleDateFormat(DateUtils.DATE_FORMAT_DD); List<List< Object>> list =
	 * new ArrayList<>(); for (Bonusinfo obj : dataList) { List<Object> temp =
	 * new ArrayList<>(); temp.add(obj.getsNo()); temp.add(obj.getsName());
	 * temp.add(obj.getClaName()); temp.add(obj.getBiOption1());
	 * temp.add(obj.getBiMoney()); temp.add(obj.getbPayee());
	 * temp.add(obj.getbPosition()); String dateStr =
	 * sdf.format(obj.getBiDate()); temp.add(dateStr);
	 * temp.add(obj.getBiRemark()); list.add(temp); } //调用我们的excel工具类，导出数据
	 * HSSFWorkbook workbook = ExcelUtil.generateExcel("奖金明细列表", new String[] {
	 * "学生学号","学生姓名","班级","奖金名目","奖金金额","领款人","领款人部门","领款时间","备注"}, list); try {
	 * ViewExcel.buildExcel(null, workbook, request, response, "奖金明细列表.xls"); }
	 * catch (Exception e) { e.printStackTrace(); } return new ModelAndView(new
	 * ViewExcel(), model); }
	 * 
	 *//**
		 * @Description:下载模板
		 * @author:dingchuan
		 * @param response
		 * @throws Exception
		 *             返回类型 void
		 * @date 2017年2月14日
		 *//*
		 * @RequestMapping(value="/downExcelModel") public void
		 * downExcelModel(HttpServletResponse response) throws Exception{ String
		 * path = WebUtil.getResourceRealPath(
		 * "WEB-INF/views/admin/bonusinfo_import_model.xlsx");
		 * FileDownload.fileDownload(response, path, "奖金明细导入模板.xlsx"); }
		 * 
		 * private static final Logger log =
		 * Logger.getLogger(BonusinfoController.class);
		 */

	/**
	 * @Description:导入excel
	 * @author:dingchuan
	 * @param response
	 * @param request
	 * @param file
	 * @return 返回类型 AjaxResult
	 * @date 2017年2月14日
	 */
	/*
	 * @RequestMapping(value = "/importData") public @ResponseBody AjaxResult
	 * importData(HttpServletResponse response, HttpServletRequest request,
	 * 
	 * @RequestParam(value = "file", required = false) MultipartFile file) { //
	 * 记录成功的导入多少条数据 int count = 0; // 构造对象的集合 List<Bonusinfo> bonusinfoList =
	 * new ArrayList<Bonusinfo>();
	 * response.setContentType("text/html;charset=UTF-8"); String fileName =
	 * file.getOriginalFilename(); String extension = fileName.lastIndexOf(".")
	 * == -1 ? "" : fileName.substring(fileName.lastIndexOf(".") + 1); if
	 * (!extension.equals("xls") && !extension.equals("xlsx")) { return new
	 * AjaxResult(AjaxResult.STATUS_OK, null, "请选择excel文件！！！"); } String dirPath
	 * = request.getSession().getServletContext().getRealPath("/") +
	 * "fileupload"; File fileDir = new File(dirPath); SimpleDateFormat sdf =
	 * new SimpleDateFormat(DateUtils.DATE_FORMAT_DD); try { if
	 * (!fileDir.exists()) { if (fileDir.mkdirs()) { } } File saveFile = new
	 * File(dirPath + "/" + fileName); file.transferTo(saveFile);
	 * List<List<Object>> list = ExcelImport.readExcel(saveFile, fileName, null,
	 * 7); // 由于读取excel的工具类会从标题行开始读取，因此，list=null或者size=1表示只有标题行说明没有数据可以导入 if
	 * (list == null || list.size() <= 1) { throw new
	 * GlobleException("没有数据可导入"); } for (int i = 2; i < list.size(); i++) {
	 * Bonusinfo bonusinfo = new Bonusinfo();//每一行 List<Object> objList =
	 * list.get(i); //遍历从0开始、Excel表的序列是从1开始 int t = i+1;
	 * 
	 * if(objList.get(0)==null){ return new AjaxResult(AjaxResult.STATUS_ERR,
	 * null, "导入失败!因为第"+t+"行的学生姓名没有填写"); }else{ String bSname =
	 * ((String)objList.get(0)).trim();//学生姓名 try { long id = 1;
	 * //studentService.findByName(bSname);//需要转成学生id存入奖金明显表 if(id==0){ return
	 * new AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的学生姓名不存在"); }
	 * Long sId = Long.valueOf(id);
	 * 
	 * bonusinfo.setsId(sId); } catch (Exception e) { log.debug(e.toString());
	 * return new AjaxResult(AjaxResult.STATUS_ERR, null,
	 * "导入失败!因为第"+t+"行的学生姓名不存在"); } }
	 * 
	 * if(objList.get(1)==null){ return new AjaxResult(AjaxResult.STATUS_ERR,
	 * null, "导入失败!因为第"+t+"行的班级没有填写"); }else{ String bclaName =
	 * ((String)objList.get(1)).trim();//班级名称
	 * 
	 * try{ long claId1 = tabClassService.findByName(bclaName); if(claId1==0){
	 * return new AjaxResult(AjaxResult.STATUS_ERR, null,
	 * "导入失败!因为第"+t+"行的班级名称不存在"); } bonusinfo.setsClass(claId1); }
	 * catch(Exception e){ log.debug(e.toString()); return new
	 * AjaxResult(AjaxResult.STATUS_ERR, null, "导入失败!因为第"+t+"行的班级和学生不匹配"); } }
	 * 
	 * if(objList.get(2)==null){ return new AjaxResult(AjaxResult.STATUS_ERR,
	 * null, "导入失败!因为第"+t+"行的奖金名目没有填写"); }else{ String biOption1 =
	 * ((String)objList.get(2)).trim();//奖金名目 bonusinfo.setBiOption1(biOption1);
	 * }
	 * 
	 * if(objList.get(3)==null){ return new AjaxResult(AjaxResult.STATUS_ERR,
	 * null, "导入失败!因为第"+t+"行的奖金金额没有填写"); }else{ String couCostStr =
	 * ((String)objList.get(3)).trim();//奖金金额 String str1;
	 * if(couCostStr.contains(".")){ str1 = couCostStr.substring(0,
	 * couCostStr.length()-3); }else{ str1 = couCostStr; } try { Long couCost =
	 * Long.valueOf(str1); bonusinfo.setBiMoney(couCost); } catch (Exception e)
	 * { log.debug(e.toString()); return new AjaxResult(AjaxResult.STATUS_ERR,
	 * null, "导入失败!因为第"+t+"行的奖金金额填写的不是数字"); } }
	 * 
	 * if(objList.get(4)==null){ return new AjaxResult(AjaxResult.STATUS_ERR,
	 * null, "导入失败!因为第"+t+"行的领款人没有填写"); }else{ String bPayee =
	 * ((String)objList.get(4)).trim();//领款人 bonusinfo.setbPayee(bPayee); }
	 * 
	 * if(objList.get(5)==null){ return new AjaxResult(AjaxResult.STATUS_ERR,
	 * null, "导入失败!因为第"+t+"行的领款人职位没有填写"); }else{ String bPosition =
	 * ((String)objList.get(5)).trim();//领款人部门
	 * bonusinfo.setbPosition(bPosition); }
	 * 
	 * if(objList.get(6)==null){ return new AjaxResult(AjaxResult.STATUS_ERR,
	 * null, "导入失败!因为第"+t+"行的领款日期没有填写"); }else{ String claDateStr =
	 * ((String)objList.get(6)).trim();//领款日期 Date date; try { date =
	 * sdf.parse(claDateStr); } catch (Exception e) { log.debug(e.toString());
	 * return new AjaxResult(AjaxResult.STATUS_ERR, null,
	 * "导入失败!因为第"+t+"行的入职时间填写格式不正确"); } bonusinfo.setBiDate(date); }
	 * if(objList.get(7)!=null){ String biRemark =
	 * ((String)objList.get(7)).trim();//备注 bonusinfo.setBiRemark(biRemark); }
	 * bonusinfoList.add(bonusinfo); } count =
	 * bonusinfoService.adds(bonusinfoList); } catch (IOException e) {
	 * log.error("导入异常"); }finally { FileUtils.deleteDir(fileDir); } if (count >
	 * 0) { return new AjaxResult(AjaxResult.STATUS_OK, null, "成功导入" + count +
	 * "条数据!"); } else { return new AjaxResult(AjaxResult.STATUS_ERR, null,
	 * "导入失败!"); } }
	 */
}